package cn.visu.security;



import cn.visu.bean.Permission;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *
 */
@Component("shiroFilterChainManager")
public class ShiroFilterChainManager {
    @Autowired
    private DefaultFilterChainManager filterChainManager;
    private Map<String, NamedFilterList> defaultFilterChains;
    @PostConstruct
    public void init() {
        defaultFilterChains =
                new HashMap<String, NamedFilterList>(filterChainManager.getFilterChains());
    }
    public void initFilterChains(List<Permission> permissionList) {
        //1、首先删除以前老的filter chain并注册默认的
        filterChainManager.getFilterChains().clear();
        if(defaultFilterChains != null) {
            filterChainManager.getFilterChains().putAll(defaultFilterChains);
        }
        //2、循环URL Filter 注册filter chain
        for (Permission perm : permissionList) {
            String url = perm.getUrl();
            //注册perms filter
            if (!StringUtils.isEmpty(perm.getName())) {
                filterChainManager.addToChain(url, "perms", perm.getName());
            }
        }
    }
}
